package sk.stuba.fiit.pki.dao.impl;

import java.util.Collection;
import java.util.List;

import org.hibernate.Transaction;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import sk.stuba.fiit.pki.dao.CrlDao;
import sk.stuba.fiit.pki.entity.CRLEntity;
import sk.stuba.fiit.pki.entity.CertificateEntity;

@Repository("crlDao")
@Transactional(readOnly = true)
public class CrlDaoImpl implements CrlDao {

	@Autowired
	protected SessionFactory sessionFactory = null;
	
	public List<CRLEntity> findCRLs() throws DataAccessException {
		Session session = sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();
		List<CRLEntity> crls = (List<CRLEntity>) session.createCriteria(CRLEntity.class).list();
		transaction.rollback();
		session.close();
		return crls;
	}

	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
	public void save(CRLEntity crlEntity) {
		Session session = sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();
		session.saveOrUpdate(crlEntity);
		transaction.commit();
		session.close();
	}

	public void delete(CRLEntity certificateEntity) {
		Session session = sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();
		session.delete(certificateEntity);
		transaction.commit();
		session.close();
	}

	public CRLEntity findCrlBySerialNumber(Integer serialNumber)
			throws DataAccessException {
		Session session = sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();
		List<CRLEntity> cert = (List<CRLEntity>) session.createCriteria(CRLEntity.class).add( Restrictions.eq("crlserialNum",serialNumber)).list();	
		transaction.rollback();	
		session.close();
		if(cert.size()>0)
			return cert.get(0);
		return new CRLEntity();
	}

}
